# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/7/24

library(ggrepel)
library(ropls)
library(optparse)
library(tidyverse)
library(magrittr)
library(extrafont)
library(jsonlite)

createWhenNoExist <- function(f) {
  !dir.exists(f) && dir.create(f)
}

p.cor <- function(n, p, method = "pearson") {
  df <- n - 2
  t <- qt(p / 2, df, lower.tail = FALSE)
  r <- switch(method,
              "pearson" = sqrt(t^2 / (df + t^2))
  )
  return(r)
}

option_list <- list(
  make_option("--g", default = "group.txt", type = "character", help = "sample group file"),
  make_option("--cc", default = "calculate_config.json", type = "character", help = "config file"),
  make_option("--pc", default = "vPlot_plot_config.txt", type = "character", help = "config file")
)
opt <- parse_args(OptionParser(option_list = option_list))
font_import(paths = c("/usr/share/fonts/myFonts"), recursive = F, prompt = F)

options(digits = 3)

args <- commandArgs(trailingOnly = F)
scriptPath <- dirname(sub("--file=", "", args[grep("--file", args)]))
source(str_c(scriptPath, "/parse_config_json.R"))
baseFamily <- fontFamily

sampleInfo <- read_tsv(opt$g) %>%
  rename(SampleID = Sample) %>%
  select(c("SampleID", "ClassNote"))

configJson <- fromJSON(opt$cc)
vipNum <- configJson$vip %>%
  as.numeric()

parent <- paste0("./")
createWhenNoExist(parent)
allFileName <- paste0(parent, "/OPLSDA_VIP.csv")
outFileName <- paste0(parent, "/OPLSDA_VPlot.pdf")
method <- "pearson"
n <- nrow(sampleInfo)
plotData <- read.csv(allFileName, header = T) %>%
  rowwise() %>%
  do({
    result <- as.data.frame(.)
    p <- result["P"]
    vip <- result["VIP"]
    col <- if (vip >= vipNum) {
      "height"
    }else "low"
    result$col <- col
    result
  }) %>%
  mutate(col = factor(col, levels = c("height", "median", "low"))) %>%
  rename(vip = VIP, cor = Corr.Coeffs.) %>%
  as.data.frame()

print(head(plotData))

leftPlotData <- plotData %>%
  filter(cor < 0) %>%
  filter(col != "low")

rightPlotData <- plotData %>%
  filter(cor > 0) %>%
  filter(col != "low")

yMax <- max(plotData$vip)
breaks <- seq(-1, 1, 0.2)
fontSize <- 1.5

pointCols <- tibble(sig = c("height", "median", "low"), col = c("#006400", "#0000FF", "grey")) %>%
  deframe()

p <- ggplot(plotData, mapping = aes(x = cor, y = vip)) +
  theme_bw(base_size = 8.8, base_family = baseFamily) +
  theme(axis.text.x = element_text(size = 9, vjust = 0.5),
        axis.text.y = element_text(size = 8.8), legend.position = 'none',
        axis.title.y = element_text(size = 11), legend.margin = margin(t = 0.3, b = 0.1, unit = 'cm'),
        legend.text = element_text(size = 6), axis.title.x = element_text(size = 11), panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(), plot.title = element_text(hjust = 0.5, size = 13)
  ) +
  ylab("VIP") +
  geom_hline(aes(yintercept = vipNum), colour = "#A9A9A9", linetype = 2, size = 0.375) +
  scale_colour_manual("", values = pointCols) +
  scale_x_continuous("Corr.Coeffs.", breaks = breaks, limits = c(-1.2, 1.2)) +
  geom_text(aes(x = cor, y = vip, colour = col), label = "+", size = 4, family = baseFamily,
            hjust = 0.5, vjust = 0.3, fontface = "bold")

if (showSample) {
  p <- p +
    geom_text(data = rightPlotData, aes(x = cor, y = vip, label = Metabolite, color = col), size = fontSize,
              family = baseFamily,
              hjust = 0, nudge_x = 0.015,) +
    geom_text(data = leftPlotData, aes(x = cor, y = vip, label = Metabolite, color = col), size = fontSize,
              family = baseFamily,
              nudge_x = -0.015, hjust = 1)
}

p <- getBasicPlotArg(p)

ggsave(limitsize = FALSE, outFileName, p, width = width, height = height)











